package com.feinno.urcs.group.http.handler;

import com.feinno.urcs.group.GroupConfiguration;
import com.feinno.urcs.group.GroupError;
import com.feinno.urcs.group.GroupException;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.entity.GroupInfo;
import com.feinno.urcs.group.entity.GroupMember;
import com.feinno.urcs.group.http.servlet.BaseHttpServlet;
import com.feinno.urcs.group.http.servlet.GroupHttpContext;
import com.feinno.urcs.group.http.util.HttpHelper;
import com.feinno.urcs.types.MobileNo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by wuzhiguo on 15-5-14.
 */
public class GroupInviteReplyHandler extends BaseHttpServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(GroupInviteReplyHandler.class);

    @Override
    public void process(final GroupHttpContext ctx) throws IOException {
        try {
            if (LOGGER.isInfoEnabled()) {
                String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
                LOGGER.info(String.format("Received Request: %s", requestString));
            }

            if (ctx.getTargetIMPU() == null) {
                String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
                LOGGER.error(String.format("targetIMPU is null. Received Request: %s", requestString));
                ctx.getResponse().sendError(400, "ArgsError");
                return;
            }

            if (!ctx.getSenderIMPU().equals(ctx.getTargetIMPU())) {
                String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
                LOGGER.error(String.format("senderIMPU not equals targetIMPU. Received Request: %s", requestString));
                ctx.getResponse().sendError(400, "ArgsError");
                return;
            }

            boolean isAccept;
            if (ctx.getBodyString().trim().equals("active")) {
                isAccept = true;
            } else if (ctx.getBodyString().trim().equals("reject")) {
                isAccept = false;
            } else {
                String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
                LOGGER.error(String.format("bodyString Error. Received Request: %s", requestString));
                ctx.getResponse().sendError(400, "ArgsError");
                return;
            }


            // 调用GroupService
//            GroupIndex groupIndex = new GroupIndex(getGroupIdFromUri(ctx.getXuiIMPU().toString()), 0);
            int groupId = getGroupIdFromUri(ctx.getXuiIMPU().toString());
            GroupIndex groupIndex = ctx.getGroupService().getGroupIndex(groupId);
            MobileNo inviteMember = MobileNo.parseFrom(ctx.getTargetIMPU().getUser());
            GroupInfo groupInfo = ctx.getGroupService().getGroupInfo(groupIndex);
//            boolean isReject = true;
            boolean isAccepted = false;
            for (GroupMember member : groupInfo.getMembers()) {
                if (member.getMobileNo().equals(inviteMember)) {
//                    isReject = false;
                    if (member.getIdentity() == 3) {
                        isAccepted = true;
                    }
                }
            }

            // 已经在其他终端同意了
            if (isAccepted) {
                ctx.getResponse().setStatus(601);
                ctx.getResponse().setHeader("ETag", "0");
                setDigestAuthenticationInfo(ctx);
                ctx.getResponse().setContentLength(0);
                return;
            }

//            // 已经在其他终端拒绝过了
//            if (isReject) {
//                ctx.getResponse().setStatus(603);
//                ctx.getResponse().setHeader("ETag", "0");
//                setDigestAuthenticationInfo(ctx);
//                ctx.getResponse().setContentLength(0);
//                return;
//            }
            boolean flag = false;
            if (isAccept) {
                if (groupInfo.getCurrentMemberCount() >= GroupConfiguration.INSTANCE.getMemberLimit()) {
                    flag = true;
                } else {
                    ctx.getGroupService().processGroupInvite(groupIndex, inviteMember, isAccept, true);
                }
            }
            ctx.getResponse().setStatus(flag ? 486 : 200);
            ctx.getResponse().setHeader("ETag", "0");
            setDigestAuthenticationInfo(ctx);
            ctx.getResponse().setContentLength(0);

            if (LOGGER.isInfoEnabled()) {
                String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
                LOGGER.info(String.format("process() Successfully. Received Request: %s", requestString));
            }

        } catch (GroupException gex) {
            GroupError error = gex.getError();
            String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
            LOGGER.error(String.format("process() GroupException. GroupError Code: %s Received Request: %s",
                    error.getSipCode(), requestString), gex);
            ctx.getResponse().sendError(error.getSipCode(), "GroupError");
        } catch (Exception ex) {
            String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
            LOGGER.error(String.format("process() Error. Received Request: %s", requestString), ex);
            ctx.getResponse().sendError(500, "ServerError");
        }
    }
}
